var tree;
var gdeptId;
var currentId;
var hostId;
var currentNode,myNode;
var quotaAction="updatequotas";
var root = {
		name : "所有产品",
		open : true,
		nocheck : true,
		id  : "root",
		key : "root",
		isParent : true
	};
var zNodes = [ root ];
$(function() {
	fillDepartments();
	$("#searchBtn").bind("click", searchNode);
	$("#saveBtn").bind("click", saveProduct);
	$("#clearBtn").bind("click", clearForCreate);
	$("#saveQuotaBtn").bind("click",saveQuota);
	$("#techBtn").bind("click",showAddTechnics);
	$("#ept").bind("click",openExport);
	codeAutoComplete("ownercode");
});

// 填充部门控件
function fillDepartments() {
	var depts = $("#depts");
	$.getJSON("admin/department/department!bytype", {
		"bean.id" : "root",
		"bean.departmentType" : "Manufacture"
	}, function(data, textStatus, jqXHR) {

		$.each(data, function(i, item) {
			// var t = item.attr['departmentType'];
			var li = $("<button did='" + item.id + "' dname='"+item.name+"' type='button' class='btn btn-info'>"
					+ item.name + "</button>");
			li.bind("click", refreshBomTree);
			depts.append(li);

		});

	});
}

function openExport(){
	window.open("product/product!dataoutput", "_eptwin_");
}
function refreshBomTree() {
	var itemType = $("#itemType").val();
	var deptId = $(this).attr("did");
	var deptName = $(this).attr("dname");
	root.name= "["+deptName+"] 的所有产品";
	gdeptId = deptId;
	var setting = {
		view : {
			// addHoverDom: addHoverDom,
			// removeHoverDom: removeHoverDom,
			selectedMulti : false,
			dblClickExpand : false,
			showLine : false
		},
		edit : {
			enable : true,
			editNameSelectAll : true,
			showRenameBtn : false,
			showRemoveBtn : true
		},
		async : {
			enable : true,
			url : "product/product!quotasnode",
			autoParam : [ "key=term" ],
			otherParam : {
				"department.id" : deptId,
				"bean.itemType" : itemType
			}
		},
		callback : {
			// onAsyncSuccess: zTreeOnAsyncSuccess,
			// onAsyncSuccess: zTreeOnAsyncSuccess,
			//onAsyncError:zTreeOnAsyncError,
			onClick : zTreeOnClickMain,
			beforeRemove : beforeRemove,
			onRemove : onRemove
		}
	};

	tree = $.fn.zTree.init($("#bomTree"), setting, zNodes);
	var nodes = tree.getNodes();
	tree.expandNode(nodes[0]);

}

function searchNode() {
	if (tree == null) {
		alert("还没有加载Bom树,请先选择部门加载该部门Bom树!");
		return;
	}
	var setting = {
		view : {
			// addHoverDom: addHoverDom,
			// removeHoverDom: removeHoverDom,
			selectedMulti : false,
			dblClickExpand : false,
			showLine : true
		},
		edit : {
			showRenameBtn : false,
			showRemoveBtn : true,
			enable : true,
			editNameSelectAll : true
		},
		async : {
			enable : true,
			url : "product/product!quotasnode",
			autoParam : [ "key=term" ],
			otherParam : {
				"department.id" : gdeptId
			}
		},
		callback : {			
			onClick : zTreeOnClickMain
		},
		data : {
			simpleData : {
				enable : true
			}
		}

	};
	var value = $("#stext").val();
	if (value == '') {
		alert("请输入查询关键字");
		return;
	}

	var nodes = tree.getNodesByParamFuzzy("name", value);

	var snodes = [ {
		"name" : "与 " + value + " 相关的产品 ",
		"open" : true,
		"id" : "root",
		"children" : nodes

	} ];
	tree = $.fn.zTree.init($("#bomTree"), setting, snodes);

}
function zTreeOnClickMain(event, treeId, treeNode) {
	
	if(treeNode.id=='root')return;
	var pdtId;
	var attrs = treeNode.attrs;
	var onquota = attrs['onquota'];	
	myNode = treeNode;
	if (!onquota) {
		currentNode = treeNode;		
		hostId = treeNode.id;
		currentId = treeNode.id;		
		pdtId = treeNode.id;
		$("#hostcode").val(pdtId);
		//alert(treeNode.children.length);
		//quotaAction = "createquotas";
	}else{
	    $("#saveQuotaBtn").html("保存定额");
		pdtId = attrs['ownercode'];
		$("#ownercode").val(pdtId);
	    var bto = attrs['hostcode'];
	    $("#hostcode").val(bto);
	    currentId = pdtId;
	    var cme = attrs['consume'];
	    $("#consume").val(cme);	   
	    quotaAction = "updatequotas";	    
	}
	
	
	$("#productCnt").load("product/product!getone", "bean.code=" + pdtId);
	
}

function zTreeOnAsyncSuccess(event, treeId, treeNode, msg){
	//alert(treeNode.children.length);
}
function zTreeOnAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
    //alert(XMLHttpRequest);
}

function clearForCreate() {
	$("#productCnt").load("product/product-new");
}
function parseProductData(data) {
	$("#productCnt").html(data);
}
function addHoverDom(treeId, treeNode) {
};

function removeHoverDom(treeId, treeNode) {
	// $("#addBtn_"+treeNode.id).unbind().remove();
};
function beforeRemove(treeId, treeNode) {
	if (treeNode.isParent){
		alert("产品不能在此删除,请转到产品列表页面删除!");
		return false;
	}
	var zTree = $.fn.zTree.getZTreeObj("bomTree");
	zTree.selectNode(treeNode);
	return confirm("确认删除该定额关系 [" + treeNode.name
			+ "]吗？\n定额关系被删除后,该定额相关产品仍然存在，不会被删除!");
}
function onRemove(e, treeId, treeNode) {
	var url = "product/product!removequotas";
	var attrs = treeNode.attrs;
	var data = "quotabeans[0].host.code=" + attrs['hostcode']+"&quotabeans[0].owner.code="+attrs['ownercode'];
	doSubmit(url, data, function() {
		var zTree = $.fn.zTree.getZTreeObj("bomTree");
		zTree.reAsyncChildNodes(treeNode, "refresh");

	});
}

function showAddTechnics(){
	window.showModalDialog("technics/technics!input?bean.product.code="+currentId);
}

function saveQuota(){
	var data = $("#qform").serialize();
	doSubmit("product/product!"+quotaAction,data,saveSuccess);	
}


function saveProduct() {
	var postdata = $("#pform").serialize();
	doSubmit("product/product!"+action, postdata, saveSuccess);
}
function saveSuccess() {
	createNotify('操作成功!');
	var mytree = $.fn.zTree.getZTreeObj("bomTree");
	var pNode = myNode.getParentNode();		
	mytree.reAsyncChildNodes(pNode, "refresh");
}

function productAutoComplateCallback(pdt){
	var spdt = $("#spdt");
	spdt.empty();
	spdt.append("<li> <span>编码 </span>:"+pdt.code+"</li>");
	spdt.append("<li> <span>名称 </span>:"+pdt.name+"</li>");
	spdt.append("<li> <span>单位 </span>:"+pdt.priceUnit+"</li>");
	spdt.append("<li> <span>价格 </span>:"+pdt.price+"</li>");	
    $("#saveQuotaBtn").html("添加定额");
    quotaAction="createquotas";
}